# 2. 导入创建的蓝图对象, 使用蓝图实现路由
from flask import abort
from flask import g
from flask import request

from info import constants, db
from info.models import News,Comment, User, CommentLike
from info.utils.common import login_user_data
from info.utils.response_code import RET
from . import news_blue
from flask import render_template, current_app, jsonify

@news_blue.route('/news_comment',methods=['POST'])
@login_user_data
def news_comment():
    #获取参数
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登陆')
    #校验参数
    news_comment=request.json.get('comment')
    news_id=request.json.get('news_id')
    parent_id=request.json.get('parent_id')

    if not all([news_comment,news_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
    #添加评论
    try:
         news=News.query.get(news_id)
    except Exception as e:
         current_app.logger.error(e)
         return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    comment=Comment()
    comment.content=news_comment
    comment.news_id=news_id
    comment.user_id=user.id
    if parent_id:
        comment.parent_id=parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')
    #返回数据

    return jsonify(errno=RET.OK,errmsg='成功',data=comment.to_dict())



@news_blue.route('/<news_id>')
@login_user_data
def news_detail(news_id):
    #1.判断用户有没有登陆,拿到用户信息
    user=g.user
    #2.查询点击排行新闻的数据
    try:
        click_news_list_models=News.query.order_by(News.clicks.desc()).limit(constants.NEWS_RANK_MAX_NEWS)
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    click_news_list=[]
    for news in click_news_list_models if click_news_list_models else []:
        click_news_list.append(news.to_basic_dict())

    #3.从数据库中根据该news_id查询该条新闻的信息
    news=None

    try:
        news=News.query.get(news_id)
    except Exception as e:
            current_app.logger.error(e)
            abort(500)

    if not news:
        abort(404)


    #4.对该新闻的点击数加一
    news.clicks+=1

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        abort(500)
    #5.判断该用户有没有收藏该新闻,默认是没有收藏
    is_collected=False
    is_followed=False
    if user:
        if news in user.collection_news:
            is_collected=True
        # if user in news.user.followers:
        #     is_followed=True
    if user and news.user:
        if user in news.user.followers:
            is_followed=True

    #6.查询所有的用户评论
    comment_list=[]
    try:
        comment_models=Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
            current_app.logger.error(e)
            comment_models=[]
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')
    #遍历所有该新闻的评论的id
    comment_id_list = [comment.id for comment in comment_models]
    #首先查一下里面有没有用户点赞过的评论,取得comment_id
    liked_id_list=[]
    if user:
        try:
            liked_comments_models=CommentLike.query.filter(CommentLike.user_id==user.id,
             CommentLike.comment_id.in_(comment_id_list)).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')
    #然后给这些comment加一个'is_like'字段 来标记已经被点赞
        liked_id_list=[comment.comment_id for comment in liked_comments_models]

    for comment in comment_models:
        comment_dict=comment.to_dict()
        comment_dict['is_like']=False
        if user and comment.id in liked_id_list:
            comment_dict['is_like']=True
        comment_list.append(comment_dict)

    #7.将查询到的模型转换成字典,并返回数据渲染模板
    data={
        'user':user.to_dict()if user else None,
        'click_news_list':click_news_list,
        'is_collected':is_collected,
        'news':news.to_dict(),
        'comment_list':comment_list,
        'is_followed':is_followed
    }
    return render_template('news/detail.html',data=data)



@news_blue.route('/news_collect',methods=['POST'])
@login_user_data
def news_collect():
    #1.获取参数,action,news_id,用户得确保登陆
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登陆')

    action=request.json.get('action')
    news_id=request.json.get('news_id')

    #2.校验参数,参数的完整性,正确性
    if not all([action,news_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if action not in['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        news=News.query.get(news_id)
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    #3.根据action进行数据库的增删

    if action=='collect':
        if news not in user.collection_news:
            user.collection_news.append(news)

    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')
    #4.返回执行结果

    return jsonify(errno=RET.OK,errmsg='成功')


@news_blue.route('/followed_user',methods=['POST'])
@login_user_data
def followed_user():
    #首先拿到json参数 action:follow unfollow  'user_id'
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='请先登陆')
    action=request.json.get('action')
    user_id=request.json.get('user_id')
    #验证参数的完整性
    if not all([action,user_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    #参数正确性
    if action not in('follow','unfollow'):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不正确')

    try:
        target_user=User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    if not target_user:
        return jsonify(errno=RET.PARAMERR,errmsg='未查询到该用户')

    #根据动作来操作用户的关注
    if action=='follow':
        if user not in target_user.followers:
            target_user.followers.append(user)
        else:
            return jsonify(errno=RET.DATAEXIST,errmsg='当前已关注')
    else:
        if user in target_user.followers:
            target_user.followers.remove(user)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库保存错误')

    return jsonify(errno=RET.OK,errmsg='操作成功')


@news_blue.route('/comment_like',methods=['POST'])
@login_user_data
def comment_like():
    #先获取参数'action','comment_id'
    user=g.user
    action=request.json.get('action')
    comment_id=request.json.get('comment_id')
    #完整性以及正确性
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登陆')

    if not all(['action','comment_id']):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if action not in('add','remove'):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不正确')

    try:
        comment=Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    if not comment:
        return jsonify(errno=RET.PARAMERR,errmsg='未查询到评论')
    #根据动作去改变数据库
    like_model=CommentLike.query.filter(CommentLike.comment_id==comment_id,CommentLike.user_id==user.id).first()
    if action=='add':
        if not like_model:
            new_like=CommentLike()
            new_like.user_id=user.id
            new_like.comment_id=comment_id
            db.session.add(new_like)
            comment.like_count+=1
        else:
            return jsonify(errno=RET.DATAERR,errmsg='已点赞')
    else:
        if like_model:
            db.session.delete(like_model)
            comment.like_count-=1

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='操作失败')

    return jsonify(errno=RET.OK,errmsg='操作成功')